<?php
          define('ACC', true);
require('./include/init.php');

session_start(); 
//print_r($_SESSION);
$userid = $_SESSION['user_id'];

//$userid = 26;

$company = new companymodel();
$companyinfo = $company->getcompanyinfo($userid);
$companyid = $companyinfo['company_id'];
$company_y = $companyinfo['company_y'];
$company_q = $companyinfo['company_q'];

$purchaseinfo = $_POST;
$purchaserawmaterialmsg = '';
$rawmaterialontheway = $company->getrawmaterialontheway($companyid);
$rawmaterialonthewayupdate = array();

if(!empty($purchaseinfo)){
    foreach($purchaseinfo as $k=>$v){
        if(($v!='')&&($v!='0')){
            $elementname = $company->getelementname($k);
            $succeed = $company->actionpurchaserawmaterial($companyid, $k, $v);
            if($succeed === false){
                $purchaserawmaterialmsg = $purchaserawmaterialmsg . '买入' . $v . '个' .$elementname . '原材料失败，因为资金不足。<br/>';
            }else{
                $purchaserawmaterialmsg = $purchaserawmaterialmsg . '买入' . $v . '个' .$elementname . '原材料成功。<br/>';
                if(array_key_exists($elementname, $rawmaterialontheway)){
                    $rawmaterialonthewayupdate[$k] = $rawmaterialontheway[$elementname] + $v; 
                }else{
                    $rawmaterialonthewayupdate[$k] = $v;                 
                }
            }
        }    
    }
    
    $cashequivalent = $company->getcash_equivalent($companyid); 
    $totalcashequivalent = 0;
    foreach($cashequivalent  as $k=>$v){
        $totalcashequivalent = $totalcashequivalent + $v;
    }
    
        echo "
    { \"purchaserawmaterialmsg\" : \"{$purchaserawmaterialmsg}\" , 
      \"totalcashequivalent\" : \"{$totalcashequivalent}\"";
      
    foreach($rawmaterialonthewayupdate as $k=>$v){
        echo ',
"numof' . $k . 'ontheway" : "' . $v . '"'; 
    }
      
    echo '
    }
    ';    
    
    
    


}

?>
